package com.zc.demo.RSA;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
/**
 * Created by zhangchi9 on 2016/12/7.
 */
public class RSACoder extends Coder{
    public static final String KEY_ALGORITHM = "RSA";   //算法
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";//签名算法
    private static final String PUBLIC_KEY = "RSAPublicKey";    //公钥
    private static final String PRIVATE_KEY = "RSAPrivateKey";  //私钥
    /**
     * 用私钥对信息生成数字签名
     * @param data
     *            加密数据
     * @param privateKey
     *            私钥
     *d @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        // 解密由base64编码的私钥
        byte[] keyBytes = decryptBASE64(privateKey);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取私钥匙对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }
}
